package com.zbs.framework.security.entity;

import com.zbs.framework.common.utils.ErrorAssert;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author: Zbs
 * @createTime: 2021/2/25 12:11
 * 这个可以重写
 */
@Data
@Slf4j
@ToString
public class SecurityUser implements UserDetails {
    //当前登录用户
    private transient LoginUser loginUser;
    //用户基本信息
    private transient Object userInfo;
    //登录其他参数
    private transient Map<String, Object> otherParameters;
    //当前权限
    private List<String> permissions;
    //用户启用禁用 false 禁用 true 启用
    private boolean isEnabled;

    public SecurityUser(LoginUser user,List<String> permissions,Object userInfo,Map<String, Object> otherParameters, boolean isEnabled) {
        if (user != null) {
            this.loginUser = user;
            this.permissions = permissions;
            this.userInfo = userInfo;
            this.otherParameters = otherParameters;
            this.isEnabled = isEnabled;
            ErrorAssert.isTrue(isEnabled,"当前用户已被禁用，不可登录");
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissions)){
            permissions.forEach(permissionValue -> {
                if(StringUtils.hasLength(permissionValue)) {
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
                    authorities.add(authority);
                }
            });
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return loginUser.getPassword();
    }

    @Override
    public String getUsername() {
        return loginUser.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return isEnabled;
    }
}
